package com.newland.boss1.zxy.controller;

import com.newland.boss1.zxy.monitor.CounterMetric;
import com.newland.boss1.zxy.monitor.GaugesMetric;
import com.newland.boss1.zxy.monitor.MethodMetric;
import io.micrometer.core.annotation.Counted;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author : zhangxuyuan
 * @Project: springbootprometheus
 * @Package com.newland.boss1.zxy.controller
 * @date Date : 2021年03月10日 10:04
 */
@RestController
public class IndexController {

    @Autowired
    MeterRegistry meterRegistry;

    @GetMapping("/")
    @Timed(value = "index",extraTags = {"url","/"},histogram = true)
    @Counted(value = "zxy_index_total",extraTags = {"url","/"})
    public String index() throws InterruptedException {
        Thread.sleep(1500);
        return "springboot prometheus " + Thread.currentThread().getName();
    }

    /**
     * 添加自定义注解，统计接口调用耗时
     * @return
     * @throws InterruptedException
     */
    @MethodMetric(name = "zxy",description = "zxy",tag = "zxy")
    @GetMapping("/test")
    public String test() throws InterruptedException {
        Random random=new Random();
        int sleepTime = random.nextInt(5000);
        Thread.sleep(sleepTime);
        return "test";
    }

    /**
     * 统计接口调用次数，prometheus数据库中可用rate({name}_total[1m])查询即rate(total_total[1m])
     * @return
     */
    @CounterMetric(name = "count" ,description = "count" , tag = {"count","/count"})
    @GetMapping("/count")
    public String count()
    {
        return "count";
    }

    /**
     * Gauge统计在线用户量
     * @return
     */
    @GaugesMetric
    @GetMapping("/login")
    public String login()
    {
        return "login";
    }

    @GaugesMetric(type = "logout")
    @GetMapping("/logout")
     public String logout()
    {
        return "logout";
    }
}
